package JDBC;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import SwingModel.CmsQuiz;
import SwingModel.CmsQuizQuestion;
import SwingModel.CmsQuizSubmission;

public class StudentQuizActivities {
	
	
	public static List<CmsQuiz> getListOfQuiz(String courseID){
		List<CmsQuiz> listOfQuiz = new ArrayList<CmsQuiz>();
		try{
			//Database Connection and Retrieve data
			CmsDatabaseConnection dCon = new CmsDatabaseConnection();
			PreparedStatement pstmt = dCon.getPreparedStatement();
			pstmt = dCon.connection.prepareStatement("select * from tests where courseID=? and TestAvailDTM<= CURRENT_TIMESTAMP and TestExpDTM > CURRENT_TIMESTAMP");
			pstmt.setString(1,courseID);
			ResultSet resultSet = pstmt.executeQuery();
			List<CmsQuizQuestion> questions = new ArrayList<CmsQuizQuestion>();

			for(int i = 0; resultSet.next(); i++){
				System.out.println("StudentQuizActivities.getListOfQuiz -Inside ResultSet");
				int testId= resultSet.getInt("TestID");
				//add quiz to the list 
				CmsQuiz quiz =new CmsQuiz(testId, resultSet.getString("TestTitle"), resultSet.getString("TestText"), resultSet.getDouble("MaxGrade"), 
						resultSet.getDouble("PercWeight"),resultSet.getTimestamp("CreatedDTM"), resultSet.getTimestamp("TestAvailDTM"), resultSet.getTimestamp("TestDueDTM"), 
						resultSet.getTimestamp("TestExpDTM"), resultSet.getInt("TestDurationMin"), questions, false);
				listOfQuiz.add(quiz);
				
			}
		} catch(Exception e){}
		
		return listOfQuiz;
		
	}	
	
	public static void setQuizStartDate(int quizID, String userName, Date startedDTM)
	{
		// TODO Set this data from GUI
		
		System.out.println("The setQuizStartDate activitiy is called on QuizID - " + quizID);
		
		try
		{
			CmsDatabaseConnection dCon = new CmsDatabaseConnection();
			
			PreparedStatement pstmt = dCon.getPreparedStatement();
		
		pstmt = dCon.connection.prepareStatement("insert into user_tests (TestId, Username, StartedDTM, IsPublisher, Grade)"
					+ "values (?, ?, ?, ?, ?);");
		
		pstmt.setInt(1,quizID);
		
		pstmt.setString(2,userName);
		
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY:MM:dd HH:mm:ss");
		
		pstmt.setString(3, sdf.format(startedDTM));
		
		pstmt.setInt(4, 0);
		
		pstmt.setDouble(5, 0);
		
		pstmt.execute();
		
		System.out.println(quizID + " - Quiz is added to the DB");
		
		System.out.println("done execution");
		} 
		
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void submitQuiz(CmsQuizSubmission quizSub)
	{
		
		System.out.println("The updateSubmittedQuiz activitiy is called on QuizID - " + quizSub.getQuizID());
		
		try
		{
			CmsDatabaseConnection dCon = new CmsDatabaseConnection();
			
			PreparedStatement pstmt = dCon.getPreparedStatement();
		
		pstmt = dCon.connection.prepareStatement("update user_tests SET SubmittedDTM=?, Grade=?, TestAnswers=? where TestId=? AND Username=?");

		SimpleDateFormat sdf = new SimpleDateFormat("YYYY:MM:dd HH:mm:ss");
		
		pstmt.setString(1,sdf.format(quizSub.getSubmittedDate()));
		
		pstmt.setDouble(2,quizSub.getGivenPoint());
		
		pstmt.setString(3, String.valueOf(quizSub.getAnswer()));
		
		pstmt.setInt(4, quizSub.getQuizID());	
		
		pstmt.setString(5, quizSub.getStudentID());
		
		pstmt.execute();
		
		System.out.println(quizSub.getQuizID()+ "Quiz is updated in the DB");
		
		System.out.println("done execution");
		} catch(Exception e){
			e.printStackTrace();
	}
	}

	public static double calculateGrade(int quizID, char[] answers, double pointPerQuestion)
	{
		System.out.println("The calculate Grade activitiy is called");
		double grades = 0;
		int correctAnswers = 0;
		try
		{
			//Database Connection and Retrieve data
			CmsDatabaseConnection dCon = new CmsDatabaseConnection();
			PreparedStatement pstmt = dCon.getPreparedStatement();
			
			pstmt = dCon.connection.prepareStatement(
						"select * from test_questions where TestID=?");
			
			pstmt.setInt(1,quizID);
			
			ResultSet questionsResultSet = pstmt.executeQuery();
			
			for(int j = 0; questionsResultSet.next(); j++)
			{
				System.out.println("Student Answer is " + String.valueOf(answers[j]) + 
						" Correct Answer is - " + questionsResultSet.getString("QuestKey"));
				if (String.valueOf(answers[j]).equalsIgnoreCase(questionsResultSet.getString("QuestKey")))
				{
					System.out.println("Answer is correct.");
					correctAnswers++;
				}
			}
			
			grades = correctAnswers * pointPerQuestion;
			
		} 
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		System.out.println("Grades are " + grades);
		
		return grades;
		
	}

	public static CmsQuizSubmission getQuizSubmission(int quizID, String studentUserName)
	{
		CmsQuizSubmission cmsQuizSubmission = null;
		
		System.out.println("The getQuizSubmission is called on QuizID - " + quizID);		
		
		try
		{
			CmsDatabaseConnection dCon = new CmsDatabaseConnection();
			
			PreparedStatement pstmt = dCon.getPreparedStatement();
		
			pstmt = dCon.connection.prepareStatement("select * from user_tests where TestId=? AND Username=?");
			
			pstmt.setInt(1,quizID);
			
			pstmt.setString(2,studentUserName);
			
			ResultSet resultSet = pstmt.executeQuery();
			
			for(int i = 0; resultSet.next(); i++){
				System.out.println("retrieveQuizSubmission -Inside ResultSet");
			
				String answers = resultSet.getString("TestAnswers");
				if(answers != null) cmsQuizSubmission = new CmsQuizSubmission(resultSet.getString("Username"), quizID, answers.toCharArray(), resultSet.getDouble("Grade"));
				else cmsQuizSubmission = new CmsQuizSubmission(resultSet.getString("Username"), quizID, null, resultSet.getDouble("Grade"));
				try{cmsQuizSubmission.setSubmittedDate(resultSet.getTimestamp("SubmittedDTM"));}catch(Exception e){};
			}
		} 
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return cmsQuizSubmission;
	}

	public static CmsQuiz retrieveQuiz(String courseId, int quizID){
		// Add the code to retrieve the Quiz from DB
		CmsQuiz result = null;
        
		try{
			//Database Connection and Retrieve data
			CmsDatabaseConnection dCon = new CmsDatabaseConnection();
			PreparedStatement pstmt = dCon.getPreparedStatement();
			
			pstmt = dCon.connection.prepareStatement(
					"select * from tests where CourseId=? and TestID=?");
			pstmt.setString(1,courseId);
			pstmt.setInt(2,  quizID);
			ResultSet resultSet = pstmt.executeQuery();
			
			
			
			for(int i = 0; resultSet.next(); i++)
			{
				System.out.println("InstructorQuizActivities.retriveQuiz -Inside ResultSet");
				List<CmsQuizQuestion> questions = new ArrayList<CmsQuizQuestion>();
				
				pstmt = dCon.connection.prepareStatement(
						"select * from test_questions where TestID=?");
				pstmt.setInt(1,quizID);
				ResultSet questionsResultSet = pstmt.executeQuery();
				for(int j = 0; questionsResultSet.next(); j++)
				{
					List<String> options = new ArrayList<String>();
					options.add(questionsResultSet.getString("QuestAText"));
					options.add(questionsResultSet.getString("QuestBText"));
					options.add(questionsResultSet.getString("QuestCText"));
					options.add(questionsResultSet.getString("QuestDText"));
					options.add(questionsResultSet.getString("QuestEText"));
					CmsQuizQuestion cmsQuizQuestion = new CmsQuizQuestion(questionsResultSet.getInt("TestQuestId"), questionsResultSet.getString("QuestText"), 
							questionsResultSet.getString("QuestKey").charAt(0), options); 
					questions.add(cmsQuizQuestion);
				}
				
				
				result = new CmsQuiz(quizID, resultSet.getString("TestTitle"), resultSet.getString("TestText"), resultSet.getDouble("MaxGrade"), 
						resultSet.getDouble("PercWeight"),resultSet.getTimestamp("CreatedDTM"), resultSet.getTimestamp("TestAvailDTM"), resultSet.getTimestamp("TestDueDTM"), 
						resultSet.getTimestamp("TestExpDTM"), resultSet.getInt("TestDurationMin"), questions, false);
				
				System.out.println(result.getQuizTitle());
			}
			
			System.out.println("done execution");
			} 
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return result;
		
	}
	

}
